/**
 * 
 */
package com.ar.myshares.daos;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;

import com.ar.myshares.model.Operation;
import com.ar.myshares.model.User;

/**
 * @author mac
 *
 */
public class UserDAOImpl implements UserDAO {

	private HibernateTemplate template;

	@Autowired
	private OperationDAO OperationDAO;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		template = new HibernateTemplate(sessionFactory);
	}

	/**
	 * @see com.ar.myshares.daos.UserDAO#getUser(long)
	 */
	@Override
	public User getUser(long id) {
		return template.get(User.class, Long.valueOf(id));
	}

	/**
	 * @see com.ar.myshares.daos.UserDAO#getAllUsers()
	 */
	@Override
	public List<User> getAllUsers() {
		return template.loadAll(User.class);
	}

	/**
	 * @see com.ar.myshares.daos.UserDAO#saveUser(com.ar.myshares.model.User)
	 */
	@Override
	public User saveUser(User user) {
		this.saveEachOperation(user);
		template.saveOrUpdate(user);
		return user;
	}

	protected void saveEachOperation(User user) {
		for (Operation eachOperation : user.getOperations()) {
			this.OperationDAO.saveOperation(eachOperation);
		}
	}

	@Override
	public User getUserByUsername(String userName) {
		DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
		criteria.add(Restrictions.eq("username", userName));
		List<?> results = this.template.findByCriteria(criteria);
		if (results.isEmpty())
			return null;
		return (User) results.get(0);
	}

	/**
	 * @see com.ar.myshares.daos.UserDAO#removeUser(com.ar.myshares.model.User)
	 */
	@Override
	public void removeUser(User user) {
		template.delete(user);
	}

	/**
	 * @return the template
	 */
	public HibernateTemplate getTemplate() {
		return template;
	}

	/**
	 * @param template
	 *            the template to set
	 */
	public void setTemplate(HibernateTemplate template) {
		this.template = template;
	}

}
